package com.itheima.admin.task;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itheima.admin.service.WemediaNewsAutoScanService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsPageReqDto;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.admin.task
 */
@Component
@Slf4j
public class SyncArticleTask {

    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private WemediaNewsAutoScanService wemediaNewsAutoScanService;

    @XxlJob("syncArticleTask")
    public ReturnT<String> syncArticleJob(String param){
        log.info("开始执行同步文章任务: param={}", param);
        //设置状态为8的数据
        WmNewsPageReqDto wmNewsPageReqDto = new WmNewsPageReqDto();
        wmNewsPageReqDto.setStatus((short)BusinessConstants.WmNewsConstants.STATUS_PASS);
        wmNewsPageReqDto.setEndPubDate(new Date());
        //远程调用微服务方法查询待发布的文章
        ResultVo<List<WmNewsVo>> listResultVo = wmNewsFeign.list4ArticleSync(wmNewsPageReqDto);
        List<WmNewsVo> wmNewsVos = listResultVo.getData();
        if(listResultVo.isSuccess()){
            if (CollectionUtils.isNotEmpty(wmNewsVos)){
                //同步到文章article
                for (WmNewsVo wmNewsVo : wmNewsVos) {
                    boolean flag = wemediaNewsAutoScanService.syncArticleInfo(wmNewsVo);
                    if(flag) {
                        log.info("同步文章数据成功: wmNewsId={}",wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据成功: wmNewsId={}",wmNewsVo.getId());
                    }else{
                        log.info("同步文章数据失败: wmNewsId={}",wmNewsVo.getId());
                        XxlJobLogger.log("同步文章数据失败: wmNewsId={}",wmNewsVo.getId());
                    }
                }

            }
            // TODO 远程调用查询文章 并处理
            log.info("同步文章任务完成: param={}", param);
            return ReturnT.SUCCESS;
        }else{
            log.info("同步文章任务失败: param={}， 调用自媒体微服查询失败", param);
            return ReturnT.FAIL;
        }


    }
}
